package com.tianmao.swing.core;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tianmao.swing.maininterface.CDFPSKDll;
import com.tianmao.swing.maininterface.Printers;

public class PrintRFID {

    public void receive(String jsonData) {
        System.setProperty("jna.encoding", "UTF-8");

        if (jsonData == null || jsonData.trim().isEmpty()) {
            System.err.println("JSON 数据为空，无法执行打印任务！");
            return;
        }

        JSONObject obj = JSONObject.parseObject(jsonData);

        try {
            int labelWidth = obj.getIntValue("width"); // 默认值为66
            int labelHeight = obj.getIntValue("height"); // 默认值为44
            int printreverse = obj.getIntValue("printreverse");//打印方向
            System.out.println("解析后的 JSON 数据: " + obj.toJSONString());
            System.out.println("标签宽度: " + labelWidth + ", 标签高度: " + labelHeight);

            JSONArray arr = obj.getJSONArray("data");
            for (int i = 0; i < arr.size(); i++) {
                JSONObject key = arr.getJSONObject(i);
                printLabel(key, labelWidth, labelHeight,i,"usb",printreverse);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void printLabel(JSONObject obj, int labelWidth, int labelHeight,int index,String type,int printreverse) {

        CDFPSKDll PrintLab = CDFPSKDll.Instance;

        // 连接打印机
        if(type.equals("usb")){
            PrintLab.PTK_OpenUSBPort(255);
        }else if(type.equals("net")){
            PrintLab.PTK_Connect_Timer("192.168.0.213",9100,2);
        }
        // 清空缓存
        PrintLab.PTK_ClearBuffer();

        int y_offer = 20;
        int mm = 12;

        // 函数返回值
        int result_printing = 0;
        // 横坐标偏移, 设置标签整体横向移动位置
        int offset_X = 0;

        // 纵坐标偏移，设置标签整体纵向移动位置
        int offset_Y = 20;

        if(type.equals("usb")){
            // 获取打印机状态
            int[] status_USB = new int[4];
            String PrinterStatus = "";
            result_printing = PrintLab.PTK_ErrorReport_USBInterrupt(status_USB);
            if (result_printing != 0) { Printers.showError("PTK_ErrorReport_USBInterrupt", result_printing); return; }
            PrinterStatus = status_USB[0] + "";
            if (!PrinterStatus.equals("0") && !PrinterStatus.equals("4"))
            {
                PrintLab.PTK_CloseUSBPort();
                System.err.println("打印机未就绪，当前错误报告：" + Printers.Status_Explain(PrinterStatus));
                return;
            }
        }

        // 清空缓存
        result_printing = PrintLab.PTK_ClearBuffer();
        if (result_printing != 0) { Printers.showError("PTK_ClearBuffer", result_printing); return; }

        // 设置打印黑度 取值范围 0-20
        result_printing = PrintLab.PTK_SetDarkness(10);
        if (result_printing != 0) { Printers.showError("PTK_SetDarkness", result_printing); return; }

        // 设置打印速度
        result_printing = PrintLab.PTK_SetPrintSpeed(4);
        if (result_printing != 0) { Printers.showError("PTK_SetPrintSpeed", result_printing); return; }

        // 设置打印方向
        if (printreverse == 1){
            result_printing = PrintLab.PTK_SetDirection('T');
        }else if(printreverse == 2){
            result_printing = PrintLab.PTK_SetDirection('B');
        }
        if (result_printing != 0) { Printers.showError("PTK_SetDirection", result_printing); return; }

        // 设置标签高度、间隙及偏移
        result_printing = PrintLab.PTK_SetLabelHeight(labelHeight*mm, 15, 0, false);
        if (result_printing != 0) { Printers.showError("PTK_SetLabelHeight", result_printing); return; }

        // 设置标签宽度，一定要准确，否则会导致打印内容位置不准确
        result_printing = PrintLab.PTK_SetLabelWidth(labelWidth*mm);
        if (result_printing != 0) { Printers.showError("PTK_SetLabelWidth", result_printing); return; }
        //资产编号
        String assetNo = "";
        try {
            JSONArray content = obj.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                JSONObject item = content.getJSONObject(i);

                // 检查 x 和 y 是否存在
                if (!item.containsKey("xmm") || !item.containsKey("ymm")) {
                    continue;
                }

                double xmm = item.getDoubleValue("xmm");
                double ymm = item.getDoubleValue("ymm");
                System.out.println(item);
                // 打印文本内容
                if (item.containsKey("lable") && !item.getString("lable").startsWith("barlable:")
                        && !item.getString("lable").startsWith("QRlable:") && !(item.containsKey("type") && item.getString("type").endsWith("code"))) {
                    String font = "宋体"; // 默认字体
                    if (item.containsKey("fontstylevalue")) {
                        font = item.getString("fontstylevalue");
                    }
                    System.out.println("字体" + font);
                    int fontsize = 48; // 默认字体大小
                    if (item.containsKey("fontsizevalue")) {
                        fontsize = item.getIntValue("fontsizevalue") * 3;
                    }
                    int fontweightvalue = 400;//默认字体粗细
                    if (item.containsKey("fontweightvalue")) {
                        fontweightvalue = item.getIntValue("fontweightvalue");
                    }
                    System.out.println("字体大小" + fontsize);
                    String lable = item.getString("lable");
                    int lineLength = 10;
                    String indent = "         "; // 定义要添加的空格，可按需调整
                    int endIndex = 16;
                    if((lable.startsWith("资产名称") || lable.startsWith("存放地点")) && lable.length() > endIndex){
                        //这个是循环的换行用法，不管汉字字母根据长度换行
                        for (int j = 0; j < lable.length(); j += lineLength) {
                            String line = "";
                            if(j == 0){
                                line = lable.substring(j, endIndex-1);
                                endIndex = endIndex-1;
                            }else{
                                int start = endIndex;
                                endIndex = Math.min(endIndex+lineLength, lable.length());
                                line = lable.substring(start, endIndex);
                                if(line.equals("")){
                                    continue;
                                }
                            }
                            if (j > 0) {
                                line = indent + line;
                            }
                            System.out.println(lable+line);
                            if(line.length() > 9){
                                PrintLab.PTK_DrawText_TrueType((int)xmm*12, (int)ymm*12+offset_Y+(j / lineLength) * fontsize, fontsize, 0, font, 1, fontweightvalue, false, false, false, line);
                            }
                        }
                    }else{
                        PrintLab.PTK_DrawText_TrueType((int)xmm*12, (int)ymm*12+offset_Y, fontsize, 0, font, 1, fontweightvalue, false, false, false, lable);
                    }
                }

                // 动态提取一维码内容
                if (item.containsKey("type") && item.getString("type").equals("barcode")) {
                    // 打印条码
                    String barcodeContent = item.getString("barcodelable_"+index); // 获取条码内容
                    String newbarcodeContent = item.getString("newbarcodelable_"+index); // 获取新编号
                    int x = (int) (xmm * 12);
                    int y = (int) (ymm * 12);
                    System.out.println("条码内容: " + barcodeContent);
                    assetNo = newbarcodeContent;
                    /*打印文字*/
                    result_printing = PrintLab.PTK_DrawBarcode(x+10, y, 0, "1",3, 0, 5 * mm, 'N', barcodeContent);
                    if (result_printing != 0) { Printers.showError("PTK_DrawText_TrueType", result_printing); return; }
                }
                //新的编码，和条码码分开了，一维码和二维码统一用一个type
                if(item.containsKey("type") && item.getString("type").equals("codeval")){
                    String qrCodeContent = item.getString("codeval_" + index); // 获取编码
                    String font = "宋体"; // 默认字体
                    if (item.containsKey("fontstylevalue")) {
                        font = item.getString("fontstylevalue");
                    }
                    System.out.println("字体" + font);
                    int fontsize = 48; // 默认字体大小
                    if (item.containsKey("fontsizevalue")) {
                        fontsize = item.getIntValue("fontsizevalue") * 3;
                    }
                    int fontweightvalue = 400;//默认字体粗细
                    if (item.containsKey("fontweightvalue")) {
                        fontweightvalue = item.getIntValue("fontweightvalue");
                    }
                    int x = (int) (xmm * 12);
                    int y = (int) (ymm * 12)-10;
                    PrintLab.PTK_DrawText_TrueType(x, y, fontsize, 0, font, 1, fontweightvalue, false, false, false, qrCodeContent);
                }

                // 动态提取二维码内容
                if (item.containsKey("type") && item.getString("type").equals("QRcode")) {
                    // 打印二维码
                    String qrCodeContent = item.getString("QRcodelable_"+index); // 获取二维码内容
                    String newqrCodeContent = item.getString("newQRcodelable_"+index); // 获取二维码内容
                    int x = (int) (xmm * 12);
                    int y = (int) (ymm * 12) + 20;
                    System.out.println("二维码内容: " + qrCodeContent);
                    assetNo = newqrCodeContent;
                    int QRcodesizevalue = 6;
                    if (item.containsKey("QRcodesizevalue")) {
                        QRcodesizevalue = item.getIntValue("QRcodesizevalue")/10;
                    }
                    PrintLab.PTK_DrawBar2D_QR(x, y, 0, 0, 0, QRcodesizevalue+2, 4, 1, 8, qrCodeContent);
                }
            }
            System.out.println("写入内容："+assetNo);
            //写入RFID，打纸质的注掉
            result_printing = PrintLab.PTK_RWRFIDLabel(1, 0, 0, 8, 1, assetNo);
            if (result_printing != 0) { Printers.showError("PTK_RWRFIDLabel", result_printing); return; }
            // 打印，必须要执行这一行，否则不会打印，打印多张标签时每张标签后面都需要加它
            result_printing = PrintLab.PTK_PrintLabel(1, 1);
            if (result_printing != 0) { Printers.showError("PTK_PrintLabel", result_printing); return; }
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            // 断开打印机连接
            PrintLab.PTK_CloseUSBPort();
        }
    }

    /**
     * 查看字符串多少非汉字字符
     */
    private int countNonChineseCharacters(String str) {
        // 使用正则表达式匹配非汉字字符
        // \p{L} 匹配所有字母，包括汉字
        // [^\p{L}] 匹配非字母字符
        // [^\u4e00-\u9fa5] 匹配非汉字字符
        String regex = "[^\\u4e00-\\u9fa5]";
        // 使用正则表达式分割字符串，统计非汉字字符的数量
        String[] nonChineseChars = str.split(regex, -1);
        // 分割后数组的长度减1即为非汉字字符的数量
        return nonChineseChars.length - 1;
    }

}